// pages/index/scene/scene.js
const app = getApp();

import {
  getGiftDetailList,
  getNewHBDetailList,
  getCBXDetailList,
  getHBQDetailList,
  getSuperDetailList,
  getRaceDetailList,
  getScoreDetailList,
  getCarnivalDetailList,
} from '../../../api/income';
import { format } from '../../../utils/date';
import { showWxToast, timeoutTask } from '../../../utils/index';
import { SHOW_COUNT, SCENARIO, WEDDING_STATUS } from '../../../config';
import { getSceneInfo, withDrawMoney, editSetting, getSignInList, moveblack, reqUpdateHbyKdRate } from '../../../api/scene';

let showCount = {
  gift: 20 || SHOW_COUNT,
  hb: 120 || SHOW_COUNT,
  cbx: 20 || SHOW_COUNT,
  hbq: 20 || SHOW_COUNT,
  super: 20 || SHOW_COUNT,
  score: 20 || SHOW_COUNT,
  carnival: 20 || SHOW_COUNT,
};

let currentPage = {
  gift: 1,
  hb: 1,
  cbx: 1,
  hbq: 1,
  score: 1,
  carnival: 1,
};

let totalPage = {
  gift: 1,
  hb: 1,
  hbq: 1,
  cbx: 1,
  score: 1,
  carnival: 1,
};
let loading = {
  gift: false,
  hb: false,
  hbq: false,
  cbx: false,
  score: false,
  carnival: false,
};
let withDrawBtnLock = false;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    currentTabIndex: 0,
    name: '',
    type: '',
    statusName: '',
    splid: '',
    date: '',
    cbx_list: [],
    hb_list: [],
    hbq_list: [],
    gift_list: [],
    super_list: [],
    score_list: [],
    carnival_income: 0,
    carnival_list: [],
    back: true,
    balance: 0,
    giftRate: 0.4,
    hbRate: 0.04,
    hbqRate: 0.5,
    kbxRate: 0.5,
    cjbpRate: 0.5,
    scoreRate: 0.5,

    topTab: 0,
  setting: [
      {
        name: '是否关闭礼物',
        desc: '开启后手机端无法发送礼物',
        id: 'hide_gift_switch',
        open: false,
        openValue: '1',
        closeValue: '0',
      },
      {
        name: '系统弹幕',
        desc: '系统不定时发送祝福礼物，活跃现场气氛，引导来宾消费',
        id: 'isSendSystemGift',
        open: false,
        openValue: '1',
        closeValue: '0',
      },
      {
        name: '来宾评价',
        desc: '来宾会对主持人老师进行评价，积累更多的评价数据',
        id: 'isNeedUserComment',
        open: false,
        openValue: '1',
        closeValue: '0',
      },
      {
        name: '隐藏手机端红包口袋余额',
        desc: '开启后手机端无法看到红包口袋余额',
        id: 'hui_suo_switch',
        open: false,
        openValue: '1',
        closeValue: '0',
      },
      {
        name: '礼物进红包口袋',
        desc: '开启后来宾发礼物的钱进入红包口袋',
        id: 'is_gift_to_hbkd',
        open: false,
        openValue: '1',
        closeValue: '0',
      },
      {
        name: '提前结束本场活动',
        desc: '开启后来宾无法进入互动页面',
        id: 'is_end_wedding',
        open: false,
        openValue: '1',
        closeValue: '0',
      },
      {
        name: '限制参与游戏',
        desc: '开启后系统会对非现场来宾进行限制，无法参与游戏',
        id: 'isLimitBuyHbq',
        open: false,
        openValue: '1',
        closeValue: '0',
      },
      {
        name: '是否禁止游戏前十名重复中奖',
        desc: '开启后竞技游戏的前十名不会重复',
        id: 'forbit_repeat_lottery',
        open: false,
        openValue: '1',
        closeValue: '0',
      },
      {
        name: '取消喵币支付',
        desc: '开启后发礼物不用充值喵币，直接支付',
        id: 'is_close_coin',
        open: false,
        openValue: '1',
        closeValue: '0',
      },
      {
        name: '本场活动设置为测试活动',
        desc: '开启后方便测试幸运夺宝、开宝等需要花钱的游戏',
        id: 'is_test_game',
        open: false,
        openValue: '1',
        closeValue: '0',
      },
    ],
    incomeRateVisible: false,

    liveUserList: [],

    hbyProportionSettingVisible: false,
    hbyProportion: 8,
  },
  toggleIncomeVisible() {
    const { incomeRateVisible } = this.data;

    this.setData({
      incomeRateVisible: !incomeRateVisible,
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      back: getCurrentPages().length > 1,
    });
    if (options.type) {
      this.setData({
        topTab: Number(options.type),
      });
    }
    if (options.scene) {
      this.setData({
        liveid: options.scene,
        scene: options.scene,
      });
    }
    if (options.splid) {
      this.setData({
        splid: options.splid,
      });
    }
    withDrawBtnLock = false;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.initSceneInfo(); //获取场次信息
    this.initOnloadData();
    if (this.data.topTab === 1) {
      this.initMyDataList();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.topTab !== 1) {
      return;
    }
    switch (this.data.currentTabIndex) {
      case 0:
        if (currentPage.gift > totalPage.gift) {
          wx.showToast({
            title: '没有更多了',
            icon: 'none',
          });
        } else {
          this.initGiftDetailList();
        }
        break;
      case 1:
        if (currentPage.hb > totalPage.hb) {
          wx.showToast({
            title: '没有更多了',
            icon: 'none',
          });
        } else {
          this.initHBDetailList();
        }
        break;
      case 2:
        if (currentPage.cbx > totalPage.cbx) {
          wx.showToast({
            title: '没有更多了',
            icon: 'none',
          });
        } else {
          this.initCBXDetailList();
        }
        break;
      case 3:
        if (currentPage.hbq > totalPage.hbq) {
          wx.showToast({
            title: '没有更多了',
            icon: 'none',
          });
        } else {
          this.initHBQDetailList();
        }
        break;
      case 4:
        if (currentPage.super > totalPage.super) {
          wx.showToast({
            title: '没有更多了',
            icon: 'none',
          });
        } else {
          this.initSuperDetailList();
        }
        break;
      case 5:
        if (currentPage.race > totalPage.race) {
          wx.showToast({
            title: '没有更多了',
            icon: 'none',
          });
        } else {
          this.initRaceDetailList();
        }
        break;
      case 6:
        if (currentPage.carnival > totalPage.carnival) {
          wx.showToast({
            title: '没有更多了',
            icon: 'none',
          });
        } else {
          this.initCarnivalDetailList();
        }
        break;
      default:
        break;
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  changeTopTabIndex(e) {
    let index = parseInt(e.currentTarget.dataset.index);
    console.log(index);
    if (index != this.data.topTab) {
      this.setData({
        topTab: Number(index),
      });
    } else {
      return;
    }
    if (this.data.topTab === 1) {
      this.initOnloadData();
      this.initMyDataList();
    } else if (this.data.topTab === 0) {
      this.initSceneInfo();
    } else if (this.data.topTab === 2) {
      this.initLiveUsers();
    }
  },

  changeTabIndex(e) {
    let index = parseInt(e.currentTarget.dataset.index);
    if (index != this.data.currentTabIndex) {
      this.setData({
        currentTabIndex: index,
      });
    } else {
      return;
    }
    this.initOnloadData();
    this.initMyDataList();
  },

  initGiftDetailList() {
    if (loading.gift) {
      return;
    }
    loading.gift = true;

    wx.showLoading({
      title: '加载中',
    });
    getGiftDetailList({
      currentPage: currentPage.gift,
      showCount: showCount.gift,
      splid: this.data.splid,
    })
      .then((res) => {
        const prelist = this.data.gift_list;
        if (res.data.list) {
          const list = res.data.list;
          for (let i = 0; i < list.length; i++) {
            list[i].gift_proportion = 0.4;
            list[i].income = list[i].gift_income;
            list[i].info.giftname = list[i].info.giftname.length > 4 ? list[i].info.giftname.slice(0, 3) + '...' : list[i].info.giftname;
          }
          currentPage.gift++;
          totalPage.gift = res.data.totalPage;
          this.setData({
            gift_list: prelist.concat(list),
          });
          console.log('gift_list', this.data.gift_list);
        }
        loading.gift = false;
        wx.hideLoading({});
      })
      .catch((err) => {
        loading.gift = false;
        wx.hideLoading({});
      });
    // .finally(() => {

    //   loading.gift = false
    //   wx.hideLoading({})
    // })
  },

  initHBDetailList() {
    if (loading.hb) {
      return;
    }
    loading.hb = true;

    wx.showLoading({
      title: '加载中',
    });
    getNewHBDetailList({
      currentPage: currentPage.hb,
      showCount: showCount.hb,
      splid: this.data.splid,
    })
      .then((res) => {
        const prelist = this.data.hb_list;

        if (res.data.list) {
          const list = res.data.list;
          for (let i = 0; i < list.length; i++) {
            //
            // list[i].date = format(list[i].create_time)
          }
          currentPage.hb++;
          totalPage.hb = res.data.totalPage || 1;
          this.setData({
            hb_list: prelist.concat(list),
          });
        }
        loading.hb = false;
        wx.hideLoading({});
      })
      .catch((err) => {
        loading.hb = false;
        wx.hideLoading({});
      });
    // .finally(() => {

    //   loading.hb = false
    //   wx.hideLoading({})
    // })
  },
  initSuperDetailList() {
    if (loading.super) {
      return;
    }
    loading.super = true;

    wx.showLoading({
      title: '加载中',
    });

    getSuperDetailList({
      currentPage: currentPage.super,
      showCount: showCount.super,
      splid: this.data.splid,
    })
      .then((res) => {
        const prelist = this.data.super_list;

        if (res.data.list) {
          const list = res.data.list;
          for (let i = 0; i < list.length; i++) {
            list[i].date = format(list[i].create_time);
            list[i].splid = this.data.splid;
          }
          currentPage.super++;
          totalPage.super = res.data.totalPage || 1;
          this.setData({
            super_list: prelist.concat(list),
            cjbpRate: list[0].rate,
          });
        }
        loading.super = false;
        wx.hideLoading({});
      })
      .catch((err) => {
        loading.super = false;
        wx.hideLoading({});
      });
  },
  initRaceDetailList() {
    if (loading.race) {
      return;
    }
    loading.race = true;

    wx.showLoading({
      title: '加载中',
    });

    getRaceDetailList({
      currentPage: currentPage.race,
      showCount: showCount.race,
      splid: this.data.splid,
    })
      .then((res) => {
        const prelist = this.data.race_list;

        if (res.data.list) {
          const list = res.data.list;
          for (let i = 0; i < list.length; i++) {
            list[i].date = format(list[i].create_time);
            list[i].splid = this.data.splid;
          }

          currentPage.race++;

          this.setData({
            race_list: prelist.concat(list),
            raceRate: list[0].race_rate,
          });
        }
        loading.race = false;
        wx.hideLoading({});
      })
      .catch((err) => {
        loading.race = false;
        wx.hideLoading({});
      });
  },
  initScoreDetailList() {
    if (loading.score) {
      return;
    }
    loading.score = true;

    wx.showLoading({
      title: '加载中',
    });

    getScoreDetailList({
      currentPage: currentPage.score,
      showCount: showCount.score,
      splid: this.data.splid,
    })
      .then((res) => {
        const prelist = this.data.score_list;

        if (res.data.list) {
          const list = res.data.list;
          for (let i = 0; i < list.length; i++) {
            list[i].date = list[i].format_create_time;
            list[i].splid = this.data.splid;
          }

          currentPage.score++;

          this.setData({
            score_list: prelist.concat(list),
            scoreRate: list[0].rate,
          });
        }
        loading.score = false;
        wx.hideLoading({});
      })
      .catch((err) => {
        loading.score = false;
        wx.hideLoading({});
      });
  },
  initCarnivalDetailList() {
    if (loading.carnival) {
      return;
    }
    loading.carnival = true;

    wx.showLoading({
      title: '加载中',
    });

    getCarnivalDetailList({
      currentPage: currentPage.carnival,
      showCount: showCount.carnival,
      splid: this.data.splid,
    })
      .then((res) => {
        const prelist = this.data.carnival_list;

        if (res.data.list) {
          const list = res.data.list;
          // 为列表中的每一项添加 splid，以便重新发送功能使用
          list.forEach((item) => {
            item.splid = this.data.splid;
          });
          currentPage.carnival++;
          totalPage.carnival = res.data.totalPage || 1;
          this.setData({
            carnival_list: prelist.concat(list),
          });
          console.log('carnival_list', this.data.carnival_list);
        }
        loading.carnival = false;
        wx.hideLoading({});
      })
      .catch((err) => {
        loading.carnival = false;
        wx.hideLoading({});
      });
  },
  initHBQDetailList() {
    if (loading.hbq) {
      return;
    }
    loading.hbq = true;

    wx.showLoading({
      title: '加载中',
    });

    getHBQDetailList({
      currentPage: currentPage.hbq,
      showCount: showCount.hbq,
      splid: this.data.splid,
    })
      .then((res) => {
        const prelist = this.data.hbq_list;

        if (res.data.list) {
          const list = res.data.list;
          for (let i = 0; i < list.length; i++) {
            //
            list[i].date = format(list[i].create_time);
          }
          currentPage.hbq++;
          totalPage.hbq = res.data.totalPage;
          this.setData({
            hbq_list: prelist.concat(list),
          });
        }
        loading.hbq = false;
        wx.hideLoading({});
      })
      .catch((err) => {
        loading.hbq = false;
        wx.hideLoading({});
      });
    // .finally(() => {

    //   loading.hb = false
    //   wx.hideLoading({})
    // })
  },
  initCBXDetailList() {
    if (loading.cbx) {
      return;
    }

    loading.cbx = true;
    wx.showLoading({
      title: '加载中',
    });
    getCBXDetailList({
      currentPage: currentPage.cbx,
      showCount: showCount.cbx,
      splid: this.data.splid,
    })
      .then((res) => {
        const prelist = this.data.cbx_list;

        if (res.data.list) {
          const list = res.data.list;
          for (let i = 0; i < list.length; i++) {
            //
            list[i].date = format(list[i].create_time);
          }
          currentPage.cbx++;
          totalPage.cbx = res.data.totalPage;
          this.setData({
            cbx_list: prelist.concat(list),
          });
        }
        loading.cbx = false;
        wx.hideLoading({});
      })
      .catch((err) => {
        loading.cbx = false;
        wx.hideLoading({});
      });
    // .finally(() => {

    //   loading.cbx = false
    //   wx.hideLoading({})
    // })
  },
  initOnloadData() {
    currentPage = {
      hb: 1,
      hbq: 1,
      cbx: 1,
      gift: 1,
      super: 1,
      score: 1,
      carnival: 1,
    };
    totalPage = {
      hb: 1,
      hbq: 1,
      cbx: 1,
      gift: 1,
      super: 1,
      score: 1,
      carnival: 1,
    };
    loading = {
      gift: false,
      hb: false,
      hbq: false,
      cbx: false,
      super: false,
      score: false,
    };
    this.setData({
      cbx_list: [],
      hb_list: [],
      hbq_list: [],
      gift_list: [],
      super_list: [],
      score_list: [],
      carnival_list: [],
    });
  },
  initMyDataList() {
    // this.clearAllData()

    switch (this.data.currentTabIndex) {
      case 0:
        this.initGiftDetailList();
        break;
      case 1:
        this.initHBDetailList();
        break;
      case 2:
        this.initCBXDetailList();
        break;
      case 3:
        this.initHBQDetailList();
        break;
      case 4:
        this.initSuperDetailList();
        break;
      case 5:
        this.initScoreDetailList();
        break;
      case 6:
        this.initCarnivalDetailList();
        break;
      default:
        break;
    }
  },
  // 获取场次信息
  initSceneInfo() {
    getSceneInfo({
      splid: this.data.splid,
    })
      .then((res) => {
        if (res.data) {
          this.handleSetting(res.data);
          const theme = res.data.theme;
          const scenario = res.data.scenario;
          const balance = res.data.balance || 0;
          const using_date = res.data.using_date;
          const game_cbx_income = res.data.earning_gegg;
          const earning_ghbq = res.data.earning_ghbq || 0;
          const earning_super = res.data.earning_super;
          const earning_score = res.data.earning_score;
          const earning_carnival = res.data.earning_carnival;
          const hbyKdRateVal = parseInt(res.data.hby_kd_rate_val, 10);
          this.setData({
            game_hb_income: res.data.game_hb_income,
            gift_income: res.data.gift_income,
            game_cbx_income: game_cbx_income,
            hbq_income: earning_ghbq,
            cjbp_income: earning_super,
            score_income: earning_score,
            carnival_income: earning_carnival,
            name: theme,
            date: using_date,
            type: SCENARIO[scenario],
            balance: balance,
            giftRate: res.data.earning_ratio,
            hbRate: res.data.hbkd_proportion,
            hbqRate: res.data.hbq_proportion,
            kbxRate: res.data.kbx_proportion,
            superRate: res.data.super_proportion,
            statusName: WEDDING_STATUS[res.data.wedding_status],
            hbyProportion: hbyKdRateVal,
          });
        }
      })
      .catch((err) => {});
  },
  promptWithDraw() {
    if (!this.data.balance) {
      wx.showToast({
        title: '可提现金额为0!',
        icon: 'none',
      });
      return;
    }
    if (parseInt(this.data.balance, 10) < 1) {
      wx.showToast({
        title: '提现金额不能小于1元!',
        icon: 'none',
      });
      return;
    }
    // 灵魂2问
    // 金额去向提问
    wx.showModal({
      title: '温馨提示',
      content: '提现金额将用于返还至活动主办方?',
      cancelText: '取消',
      confirmText: '确认',
      success: (res) => {
        const { confirm } = res;
        if (confirm) {
          // 提现提问
          let title = this.data.name || '';
          wx.showModal({
            title: title,
            content: '您确认要提现吗',
            cancelText: '取消',
            confirmText: '确认提现',
            success: (res) => {
              const { confirm } = res;
              if (confirm) {
                this.withDraw();
              } else {
                showWxToast('取消提现');
              }
            },
            fail: () => {},
          });
        } else {
          showWxToast('取消提现');
        }
      },
      fail: () => {},
    });
  },
  withDraw() {
    if (withDrawBtnLock) {
      return;
    }
    withDrawBtnLock = true;
    if (!this.data.balance) {
      wx.showToast({
        title: '可提现金额为0!',
        icon: 'none',
      });
      return;
    }
    if (parseInt(this.data.balance, 10) < 1) {
      wx.showToast({
        title: '提现金额不能小于1元!',
        icon: 'none',
      });
      return;
    }
    withDrawMoney(this.data.splid)
      .then((res) => {
        withDrawBtnLock = false;

        wx.showToast({
          title: res.msg,
          icon: 'none',
        });
        this.setData({
          balance: 0,
        });
        if (res.flag === '3') {
          // 提现成功 重新获取数据
          timeoutTask(() => {
            this.initSceneInfo();
          }, 1000);
        }
      })
      .catch((err) => {
        wx.showToast({
          title: '提现失败',
          icon: 'none',
        });
        withDrawBtnLock = false;
      });
  },
  handleSetting(data) {
    let newSetting = JSON.parse(JSON.stringify(this.data.setting));
    let actions = newSetting.filter((x) => x.id);
    actions.forEach((item, index) => {
      let result = false;
      if (!data[item.id]) {
      } else {
        result = item.openValue === data[item.id];
      }

      newSetting[index].open = result;
    });
    this.setData({
      setting: newSetting,
    });
  },
  changeSetting(e) {
    const { value } = e.detail;
    const action = e.currentTarget.id;

    const settingIndex = this.data.setting.findIndex((set) => set.id === action);
    // return ;
    const setting = this.data.setting[settingIndex];
    const newSetting = JSON.parse(JSON.stringify(this.data.setting));

    if (!action) {
      wx.showToast({
        title: '无法设置',
        icon: 'none',
      });
      return;
    }

    editSetting({
      key: action,
      value: value ? setting.openValue : setting.closeValue,
      splid: this.data.splid,
    })
      .then((res) => {
        wx.showToast({
          title: '设置成功',
          icon: 'none',
        });
        newSetting[settingIndex].open = value;
        this.setData({
          setting: newSetting,
        });
      })
      .catch((err) => {
        wx.showToast({
          title: '设置失败',
          icon: 'none',
        });
        newSetting[settingIndex].open = !value;
        this.setData({
          setting: newSetting,
        });
      });
  },

  toGiftAllFree(e) {
    const { splid } = this.data;
    wx.navigateTo({
      url: `/pages/index/giftAllFree/giftAllFree?splid=${splid}`,
    });
  },

  initLiveUsers() {
    getSignInList(this.data.splid)
      .then((res) => {
        console.log(res);
        this.setData({
          liveUserList: res.data.list.map((item) => ({
            ...item,
            phonenumber: !item.phonenumber ? '未填写手机号' : '',
          })),
        });
      })
      .catch((err) => {
        console.log(err);
      });
  },
  changeBlackSheetSwitch(e) {
    const tmpResult = e.detail.value ? '1' : '0';
    const tmpUserId = e.currentTarget.dataset.userid;
    moveblack({
      userId: tmpUserId,
      splid: this.data.splid,
      type: tmpResult,
    })
      .then((res) => {
        console.log(res);
        showWxToast('操作成功!');
      })
      .catch((err) => {
        console.log(err);
        showWxToast('操作失败!');
      });
  },
  showHbyProportionSetting() {
    this.setData({
      hbyProportionSettingVisible: true,
    });
  },
  onHbyProportionDragStart() {
    this.setData({
      hbyProportion: '',
    });
  },
  onHbyProportionSettingChange(e) {
    console.log(e.detail);
    this.setData({
      hbyProportion: e.detail,
    });
  },
  onConfirmHbyProportion() {
    wx.showLoading({
      title: '请求中...',
      mask: true,
    });
    reqUpdateHbyKdRate({
      splid: this.data.splid,
      hby_kd_rate_val: String(this.data.hbyProportion),
    })
      .then((res) => {
        console.log(res);
        wx.hideLoading();
        wx.showToast({
          title: '设置成功!',
          icon: 'success',
        });
      })
      .catch((err) => {
        console.log(err);
        wx.hideLoading();
      });
  },
});
